package com.flsldl.mydb.backend.vm;

import com.flsldl.mydb.backend.tm.TransactionManagerImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Transaction
 * @Description vm 对一个事务的抽象
 * @Author @O_o @Date 2023/2/25 下午 8:39
 */
public class Transaction {

    public long xid;
    public int level;
    public Map<Long, Boolean> snapshot; // 快照
    public Exception err;
    public boolean autoAborted;

    // 构造方法中的 active，保存着当前所有 active 的事务
    public static Transaction newTransaction(long xid, int level, Map<Long, Transaction> active) {
        Transaction t = new Transaction();
        t.xid = xid;
        t.level = level;
        if (level != 0) {
            t.snapshot = new HashMap<>();
            for (Long x : active.keySet()) {
                t.snapshot.put(x, true);
            }
        }
        return t;
    }

    public boolean isInSnapshot(long xid) {
        if (xid == TransactionManagerImpl.SUPER_XID) {
            return false;
        }
        return snapshot.containsKey(xid);
    }
}
